package com.xiyili.topspecialty;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.annotation.TargetApi;
import android.app.SearchManager;
import android.app.SearchManager.OnCancelListener;
import android.app.SearchManager.OnDismissListener;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.umeng.fb.FeedbackAgent;
import com.umeng.update.UmengUpdateAgent;
import com.xiyili.topspecialty.FineCourseCategoryListFragment.OnSpecialtyCategoryItemSelectedListener;
import com.xiyili.topspecialty.SchoolListFragment.OnSchoolSelectedListener;
import com.xiyili.topspecialty.SpecialtyListFragment.OnSpecialtyItemSelectedListener;
import com.xiyili.topspecialty.data.School;
import com.xiyili.topspecialty.data.SpecialtyItem;


public class MainActivity extends BaseFragmentActivity implements OnSchoolSelectedListener,
        OnSpecialtyItemSelectedListener, OnItemClickListener, OnSpecialtyCategoryItemSelectedListener {

    /**
     * The serialization (saved instance state) Bundle key representing the
     * current dropdown position.
     */
    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
    private boolean mTwoPane;
    private static final int SECTION_BY_SPECIALTY = 0;
    private static final int SECTION_BY_SCHOOL = 1;
    private static final int SECTION_BY_FINE_COURSE = 2;
    private static final int SECTION_BY_COUNTRY_ONE_LEVEL = 3;
    private static final int SECTION_SHARE = 4;
    private int currentSection = SECTION_BY_SPECIALTY;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] mPlanetTitles;
    private boolean exit;

    private Toolbar mToolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        UmengUpdateAgent.update(this);
        setContentView(R.layout.activity_main);

        mToolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(mToolbar);
        mTwoPane = false;

        mPlanetTitles = getResources().getStringArray(R.array.drawer_module_array);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);
        mTitle = mDrawerTitle = getTitle();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set the adapter for the list view
        mDrawerList.setAdapter(new DrawerListAdapter(this, mPlanetTitles));
        mDrawerList.setOnItemClickListener(this);


        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle  = new ActionBarDrawerToggle(this,mDrawerLayout,mToolbar,R.string.drawer_open,R.string.drawer_close);
        mDrawerToggle.setDrawerIndicatorEnabled(true);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        currentSection = 0;
        if (savedInstanceState != null) {
            if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
                currentSection = savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM);
            }
        }
        handleIntent(getIntent());

    }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            SearchManager sm = (SearchManager) getSystemService(SEARCH_SERVICE);
            sm.setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss() {
                    resetFragment();
                }
            });
            sm.setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel() {
                    resetFragment();
                }
            });
            showFragment(query);
        } else {
            selectItem(currentSection);
        }
    }


    protected void resetFragment() {
        selectItem(currentSection);

    }

    @Override
    protected void setupActionbar() {
        super.setupActionbar();
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    static class DrawerListAdapter extends ArrayAdapter<String> {
        private final LayoutInflater mInflater;
        static final int mLayoutResID = R.layout.drawer_list_item;

        public DrawerListAdapter(Context context, String[] data) {
            super(context, mLayoutResID, data);
            mInflater = LayoutInflater.from(context);

        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.drawer_list_item, parent, false);
                holder = new ViewHolder();
                holder.title = (TextView) convertView.findViewById(R.id.title);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.title.setText("" + getItem(position));

            return convertView;
        }

        static class ViewHolder {
            public TextView title;
        }

    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        selectItem(position);

    }

    /**
     * Swaps fragments in the main content view
     */
    private void selectItem(int position) {
        System.out.println("selectItem");
        // Create a new fragment and specify the planet to show based on position
        Fragment fragment = null;
        currentSection = position;
        if (currentSection == SECTION_BY_SPECIALTY) {
            fragment = new SpecialtyListFragment();
        } else if (currentSection == SECTION_BY_SCHOOL) {
            fragment = new SchoolListFragment();
        } else if (currentSection == SECTION_BY_FINE_COURSE) {
            fragment = new FineCourseCategoryListFragment();
        } else if (currentSection == SECTION_BY_COUNTRY_ONE_LEVEL) {
            fragment = new OneLevelSpecialtyListFragment();
        } else if (currentSection == SECTION_SHARE) {
            share();
            return;
        }

        // Insert the fragment by replacing any existing fragment
        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.container, fragment)
                    .commit();
        }

        // Highlight the selected item, update the title, and close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mPlanetTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    private void share() {
        String path = "/data/app";
        String packageName = getPackageName();
        PackageManager pm = getPackageManager();
        String versionName = null;
        try {
            PackageInfo pi = pm.getPackageInfo(packageName, 0);
            versionName = pi.versionName;
        } catch (NameNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        String full_path = null;
        for (int i = 1; i < 100; i++) {
            String fileName = path + "/" + packageName + "-" + i + ".apk";
            File file = new File(fileName);
            if (file.exists()) {
                full_path = fileName;
                break;
            }
        }
        if (full_path != null) {
            String dirName = "KeBiao";
            File dir = new File(Environment.getExternalStorageDirectory(), dirName);
            dir.mkdirs();
            StringBuilder sb = new StringBuilder();
            sb.append("kebiao-");
            if (versionName != null) {
                sb.append(versionName);
            }
            sb.append(".apk");
            String output_filename = sb.toString();
            File dest_file = new File(dir, output_filename);
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(full_path));
                int b;
                while ((b = in.read()) != -1) {
                    baos.write(b);
                }
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest_file));
                out.write(baos.toByteArray());
                out.flush();
                out.close();
                ToastUtils.showSuccess(this, "创建分享文件成功");
                Intent intent = new Intent(this, ShareActivity.class);
                intent.putExtra("FILE_DIR", dirName);
                intent.putExtra("FILE_NAME", output_filename);
                intent.putExtra("FILE_ABSOLUTE_PATH", dest_file.getAbsolutePath());
                startActivity(intent);

            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                ToastUtils.showSuccess(this, "创建分享文件失败");
            }
        } else {
            ToastUtils.showFailure(this, "无法分享");
        }

    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // Serialize the current dropdown position.
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, currentSection);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        // Get the SearchView and set the searchable configuration
        MenuItem menuItem = menu.findItem(R.id.action_search);
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        if (searchView == null) {
            Log.e("onCreateOptionsMenu", "searchView is null");
            return true;
        }
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                showFragment(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // TODO Auto-generated method stub
                showFragment(newText);
                return true;
            }
        });
        // Assumes current activity is the searchable activity
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        searchView.setIconifiedByDefault(true);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_feedback:
                FeedbackAgent agent = new FeedbackAgent(this);
                agent.startFeedbackActivity();
                return true;
            default:
                break;
        }

        return super.onOptionsItemSelected(item);
    }


    private void showFragment(String keyword) {
        System.out.println(currentSection + "#" + keyword);
        Fragment fragment = null;
        if (currentSection == SECTION_BY_SPECIALTY) {
            fragment = new SpecialtyListFragment();
        } else if (currentSection == SECTION_BY_SCHOOL) {
            fragment = new SchoolListFragment();
        } else if (currentSection == SECTION_BY_COUNTRY_ONE_LEVEL) {
            fragment = new OneLevelSpecialtyListFragment();
        }
        if (fragment != null) {
            if (!TextUtils.isEmpty(keyword)) {
                Bundle arguments = new Bundle();
                arguments.putString("keyword", keyword);
                fragment.setArguments(arguments);
            }
            try {
                getSupportFragmentManager().beginTransaction()
                        .replace(R.id.container, fragment).commit();
            } catch (Exception e) {
                // TODO: handle exception
                Log.e("showFragment", e.getMessage());
            }
        }
    }

    final Handler mHandler = new Handler();

    final Runnable mCancelStaleExitFlagTask = new Runnable() {
        @Override
        public void run() {
            exit = false;
            mHandler.removeCallbacks(mCancelStaleExitFlagTask);
        }
    };

    @Override
    public void onBackPressed() {
        if (exit) {
            super.onBackPressed();
        } else {
            exit = true;
            Toast.makeText(this, "紧接着再按一次退出!", Toast.LENGTH_SHORT).show();
            mHandler.postDelayed(mCancelStaleExitFlagTask, 3 * 1000);// 6 second
            if (!mDrawerLayout.isDrawerOpen(mDrawerList)) {
                mDrawerLayout.openDrawer(mDrawerList);
            }
        }

    }


    /**
     * Callback method from
     * {@link SpecialtyListFragment.OnSpecialtyItemSelectedListener} indicating
     * that the item with the given ID was selected.
     */
    @Override
    public void onSpecialtyItemSelected(SpecialtyItem item) {
        if (mTwoPane) {
            // In two-pane mode, show the detail view in this activity by
            // adding or replacing the detail fragment using a
            // fragment transaction.
            Bundle arguments = new Bundle();
            arguments.putString(TopSchoolListFragment.EXTRA_SPECIALTY_CODE,
                    item.code);
            arguments.putString(TopSchoolListFragment.EXTRA_SPECIALTY_NAME,
                    item.name);
            TopSchoolListFragment fragment = new TopSchoolListFragment();
            fragment.setArguments(arguments);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.specialty_detail_container, fragment)
                    .commit();

        } else {
            // In single-pane mode, simply start the detail activity
            // for the selected item ID.
            Intent detailIntent = new Intent(this,
                    TopSchoolListActivity.class);
            detailIntent.putExtra(
                    TopSchoolListFragment.EXTRA_SPECIALTY_CODE, item.code);
            detailIntent.putExtra(
                    TopSchoolListFragment.EXTRA_SPECIALTY_NAME, item.name);
            startActivity(detailIntent);
        }
    }

    @Override
    public void onSchoolSelected(School item) {
        // In single-pane mode, simply start the detail activity
        // for the selected item ID.
        Intent detailIntent = new Intent(this,
                TopSpecialtyListActivity.class);
        detailIntent.putExtra(
                TopSpecialtyListFragment.EXTRA_SCHOOL_CODE, item.schoolCode);
        detailIntent.putExtra(
                TopSpecialtyListFragment.EXTRA_SCHOOL_NAME, item.schoolName);
        startActivity(detailIntent);

    }

    @Override
    public void onSpecialtyCategoryItemSelected(String category) {
        Intent intent = new Intent(this, FineCourseListActivity.class);
        intent.putExtra("category", category);
        startActivity(intent);
    }

}
